package com.ig.controller;

import com.ig.controller.model.Users;
import com.ig.controller.service.Thumbnail;
import com.ig.controller.service.Upload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/")
public class ImageController {

    //使用Autowired时，该业务类需要声明为@service，此时xml中不用其它的配置
    @Autowired
    private Upload upload;
    @Autowired
    private Thumbnail thumbnail;

    //文件上传并生成缩略图
    @RequestMapping(value="/thumb",method= RequestMethod.POST)
    public String GenerateImage(@RequestParam("image") CommonsMultipartFile file, HttpServletRequest request) throws IOException
    {
        //根据相对路径获取绝对路径，图片上传后位于元数据中
        String realUploadPath=request.getServletContext().getRealPath("/")+"images";

        //获取上传后原图的相对地址
        String imageUrl=upload.uploadImage(file, realUploadPath);

        //获取生成的缩略图的相对地址
        String thumbImageUrl=thumbnail.generateThumbnail(file, realUploadPath);
        return "success";
    }


    //显示所有图片
    @RequestMapping(value="/images",method=RequestMethod.GET)
    public ModelAndView showImages(HttpServletRequest request, HttpServletResponse response)
    {
        //根据相对路径获取绝对路径，图片上传后位于元数据中
        List<String> rawImagesList=new ArrayList<String>();
        String realUploadPath=request.getServletContext().getRealPath("/")+"images";
        rawImagesList=ImageList.printFile(realUploadPath+"/rawImages");

        ModelAndView mv=new ModelAndView();
        mv.addObject("imageList", rawImagesList);
        mv.setViewName("images");
        return mv;
    }


    @RequestMapping("/uploads"   )
    public String addFile(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){

        for(int i = 0;i<files.length;i++){
            System.out.println("fileName---------->" + files[i].getOriginalFilename());

            if(!files[i].isEmpty()){
                int pre = (int) System.currentTimeMillis();
                try {
                    //拿到输出流，同时重命名上传的文件
                    FileOutputStream os = new FileOutputStream("H:/" + new Date().getTime() + files[i].getOriginalFilename());
                    //拿到上传文件的输入流
                    FileInputStream in = (FileInputStream) files[i].getInputStream();

                    //以写字节的方式写文件
                    int b = 0;
                    while((b=in.read()) != -1){
                        os.write(b);
                    }
                    os.flush();
                    os.close();
                    in.close();
                    int finaltime = (int) System.currentTimeMillis();
                    System.out.println(finaltime - pre);

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("上传出错");
                }
            }
        }
        return "/success";
    }


    @RequestMapping(value="/upload",method=RequestMethod.POST)
    private String fildUpload(Users users , @RequestParam(value="file",required=false) MultipartFile[] file,
                              HttpServletRequest request)throws Exception {
        //基本表单
        System.out.println(users.toString());

        //获得物理路径webapp所在路径
//        String pathRoot = request.getSession().getServletContext().getRealPath("");
        //根据相对路径获取绝对路径，图片上传后位于元数据中
        String pathRoot=request.getServletContext().getRealPath("/")+"images";
        String path = "";
        List<String> listImagePath = new ArrayList<String>();
        for (MultipartFile mf : file) {
            if (!mf.isEmpty()) {
                //生成uuid作为文件名称
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                //获得文件类型（可以判断如果不是图片，禁止上传）
                String contentType = mf.getContentType();
                //获得文件后缀名称
                String imageName = contentType.substring(contentType.indexOf("/") + 1);
                path = "/static/images/" + uuid + "." + imageName;
                mf.transferTo(new File(pathRoot + path));
                listImagePath.add(path);
            }
        }
        System.out.println(path);
        request.setAttribute("imagesPathList", listImagePath);
        return "success";
    }

        @RequestMapping("upload")
        public Map<String, String> upload(@RequestParam("image") MultipartFile[] mfile, HttpServletRequest request) throws IOException {
            //这里mfile可以接受前台的文件，可以是一个，也可以是多个，这正是MultipartFile强大的地方。
            HashMap<String, String> map=new HashMap<String, String>();
            //建一个Map便于返回json
            String filePath =null;String
                    fileName[]=new String[mfile.length];
            //根据传递文件个数返回文件（{msg1:"sss.png",msg2:"aa.jpg"}）
            if (mfile != null && mfile.length > 0) {
                //判断使用有文件上传
                for (int i = 0; i < mfile.length; i++) {
                    //循环上传（多文件上传）
                    try {
                        Calendar cale = null;	cale = Calendar.getInstance();	int year = cale.get(Calendar.YEAR);	int month = cale.get(Calendar.MONTH) + 1;
                        int day = cale.get(Calendar.DATE);
                        //给图片重命名加上日期前缀
                        filePath= request.getSession().getServletContext().getRealPath("/") ;
                        //获取服务器img文件夹地址（这里指的是local:8080/项目名/img）
                        fileName[i]= "/img/" + year + ""+ month + "" + day + "_" + mfile[i].getOriginalFilename();
                        //重命名图片。
                        String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
                        //截取文件后缀判断是否是一张图片
                        if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
                            int length = mfile[i].getBytes().length;
                            if (!((length / 1000) > 5120)) {
                                //判断图片地址
                                map.put("msg"+i, fileName[i]);
                                //将图片输出到制定的文件夹目录中
                                mfile[i].transferTo(new File(filePath,fileName[i]));
                            }else{
                                map.put("msg", "图片过大");
                            }}else{
                            map.put("msg", "只能上传图片啊亲!");}
                    } catch (Exception e) {
                        e.printStackTrace();
                        map.put("msg", "上传失败");}}} else {
                map.put("msg", "请选择文件");}
            return map;
        }

    @RequestMapping(value="/uploadBase64",method=RequestMethod.POST)
    //@ResponseBody Scope
    public String base64UpLoad(@RequestParam String base64Data, HttpServletRequest request, HttpServletResponse response){
        try{
            String dataPrix = "";
            String data = "";
            if(base64Data == null || "".equals(base64Data)){
                throw new Exception("上传失败，上传图片数据为空");
            }else{
                String [] d = base64Data.split("base64,");
                if(d != null && d.length == 2){
                    dataPrix = d[0];
                    data = d[1];
                }else{
                    throw new Exception("上传失败，数据不合法");
                }
            }
            String suffix = "";
            if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//编码的jpeg图片数据
                suffix = ".jpg";
            } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//编码的icon图片数据
                suffix = ".ico";
            } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//编码的gif图片数据
                suffix = ".gif";
            } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//编码的png图片数据
                suffix = ".png";
            }else{
                throw new Exception("上传图片格式不合法");
            }
            String tempFileName = UUID.randomUUID().toString() + suffix;

            //因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
            byte[] bs = Base64Utils.decodeFromString(data);
            try{
                //使用apache提供的工具类操作流
               // System.out.println(request.getServletContext().getRealPath("/upload"));
                FileUtils.writeByteArrayToFile(new File(request.getServletContext().getRealPath("/images"), tempFileName), bs);
            }catch(Exception ee){
                throw new Exception("上传失败，写入文件失败，"+ee.getMessage());
            }
            return "success";
        }catch (Exception e) {
            return "error";
        }
    }




    /**
     * 上传单个文件操作
     * @param RequestParam  括号中的参数名file和表单的input节点的name属性值一致
     * @return
     */
    @RequestMapping(value="/doUpload", method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file") MultipartFile file){
        if(!file.isEmpty()){
            try {

                //这里将上传得到的文件保存至 d:\\temp\\file 目录
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\temp\\file\\",
                        System.currentTimeMillis()+ file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "success";  //上传成功则跳转至此success.jsp页面
    }

    /**
     * 上传多个附件的操作类
     * @param multiRequest
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/doMultiUpload", method=RequestMethod.POST)
    public String doUploadFile2(MultipartHttpServletRequest multiRequest) throws IOException{

        Iterator<String> filesNames = multiRequest.getFileNames(); //获得所有的文件名
        while(filesNames.hasNext()){    //迭代，对单个文件进行操作
            String fileName =filesNames.next();
            MultipartFile file =  multiRequest.getFile(fileName);
            if(!file.isEmpty()){
               // log.debug("Process file: {}", file.getOriginalFilename());
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\temp\\imooc\\",
                        System.currentTimeMillis()+ file.getOriginalFilename()));
            }
        }
        return "success";
    }

    //文件下载
    @RequestMapping("/download")
    public void download(HttpServletRequest request,HttpServletResponse response) throws IOException
    {
        String path=request.getServletContext().getRealPath("/")+"/images/rawImages/";
        String fileName=request.getParameter("filename");
        File file=new File(path+fileName);
        if(file.exists()){
            //设置MIME类型
            response.setContentType("application/octet-stream");
            //或者为response.setContentType("application/x-msdownload");

            //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
            response.addHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes(), "ISO-8859-1"));

            InputStream inputStream=new FileInputStream(file);
            ServletOutputStream outputStream=response.getOutputStream();
            byte[] bs=new byte[1024];
            while((inputStream.read(bs)>0)){
                outputStream.write(bs);
            }
            outputStream.close();
            inputStream.close();
        }
    }


}
